<template>
    <div class="update-photo">
        <img class="img" :src="img" ref="img">
        <div class="toolbar">
            <div class="cancel" @click="$emit('close')">取消</div>
            <div class="confirm" @click="onConfirm">完成</div>
        </div>
    </div>
</template>

<script>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
import { updateUserPhoto } from '@/api/user'
export default {
    name: 'UpdateImg',
    data() {
        return {
            cropper: ''
        }
    },
    props: {
        img: {
            type: [String, Object],
            required: true
        }
    },
    created() {
    },
    computed: {
    },
    methods: {
        onConfirm() {
            // console.log(this.cropper.getData());
            this.cropper.getCroppedCanvas().toBlob(blob => {
                this.updatePhoto(blob)
            })
        },
        async updatePhoto(blob) {
            try {
                this.$toast.loading({
                    messege: '更新中',
                    forbidClick: true,
                    duration: 0 //持续展示toast
                })
                const formData = new FormData();
                formData.append('photo', blob);
                const res = await updateUserPhoto(formData)
                this.$emit('close') // 关闭弹窗
                this.$emit('update-photo', res.data.photo)
                console.log(res.data.data.photo);
                this.$toast('头像更新成功')
            } catch (error) {
                this.$toast('更新头像失败', error)
            }
        }
    },
    mounted() {
        const image = this.$refs.img
        const cropper = new Cropper(image, {
            viewMode: 1, // 只能在裁剪的图片范围内移动
            dragMode: 'move', // 画布和图片都可以移动
            aspectRatio: 1, // 裁剪区默认正方形
            autoCropArea: 1, // 自动调整裁剪图片
            cropBoxMovable: false, // 禁止裁剪区移动
            cropBoxResizable: false, // 禁止裁剪区缩放
            background: false // 关闭默认背景
        })
        this.cropper = cropper
    }

}
</script>
<style lang='less'  scoped>
.update-photo {
    background-color: #000;
    height: 100%;
    width: 100%;

    .toolbar {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        justify-content: space-between;

        .cancel,
        .confirm {
            width: 45px;
            height: 45px;
            font-size: 15px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
        }
    }
}

.img {
    width: 100%;
    display: block;
}
</style>
